<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import CommentNode from './CommentNode.vue'
import { getCommentsAPI, addCommentAPI, addLikeAPI } from '@/apis/comment'
import { useRoute } from 'vue-router';
const route = useRoute()
const isView = ref(false)
// 获取评论
const comments = reactive([])
const getComments = async () => {
    const res = await getCommentsAPI(route.params.id)
    console.log(res.data);
    Object.assign(comments, res.data) // 保持响应性
}
onMounted(() => getComments())
// 评论数据
const newComment = reactive({
    content: '',
    parentId: null,
    parentUsername: '',
    level: '1'
})

// 获取所有一级评论（按时间倒序）
const parentComments = computed(() => {
    return comments
        .filter(c => c.level === 0)
        .sort((a, b) => b.createTime - a.createTime)
})

// 获取子评论（包括所有后代回复）
const getChildComments = (parentId) => {
    // 获取直接子评论
    const Children = comments.filter(c => c.parentId === parentId || c.rootParentId === parentId)
        .sort((a, b) => a.createTime - b.createTime) // 按时间正序排列
    return Children
}

// 回复提示文字
const replyPlaceholder = computed(() =>
    newComment.parentId
        ? `回复 @${newComment.parentUsername}`
        : '请输入您的评论'
)

// 提交评论
const submitComment = async () => {
    if (!newComment.content.trim()) return
    await addCommentAPI(newComment)
    isView.value = false
    resetCommentForm()
    getComments()
    ElMessage.success('评论发表成功')
}

// 处理回复
const handleReply = (comment) => {
    isView.value = true
    newComment.parentId = comment.id
    newComment.parentUsername = comment.username
}

// 取消回复
const cancelReply = () => {
    isView.value = false
    resetCommentForm()
}

// 重置表单
const resetCommentForm = () => {
    newComment.content = ''
    newComment.parentId = null
    newComment.parentUsername = ''
}

// 处理点赞
const handleLike = async (comment) => {
    const res = await addLikeAPI(comment.id)
    if (res.data.code === 0) {
        //注册成功
        ElMessage.success(res.data.message ? res.data.message : '点赞成功')
    } else {
        //失败
        ElMessage.error(res.data.message ? res.data.message : '点赞失败')
    }
    getComments()
}
</script>

<template>



    <div class="comment-container">
        <!-- 评论输入框 -->
        <el-dialog v-model="isView" width="50%" center>
            <!-- 评论输入框 -->
            <el-card class="comment-form">
                <el-input v-model="newComment.content" type="textarea" :rows="3"
                    :placeholder="replyPlaceholder"></el-input>
                <div class="submit-area">
                    <el-button type="primary" @click="submitComment" :disabled="!newComment.content.trim()">
                        发表评论
                    </el-button>
                    <el-button v-if="newComment.parentId" @click="cancelReply">
                        取消回复
                    </el-button>
                </div>
            </el-card>
        </el-dialog>
        <!-- 评论列表 -->
        <div class="comment-list">
            <template v-for="parent in parentComments" :key="parent.id">
                <!-- 一级评论 -->
                <comment-node :comment="parent" :all-comments="comments" @reply="handleReply" @like="handleLike" />

                <!-- 二级评论（包含所有子回复） -->
                <div class="child-comments">
                    <comment-node v-for="child in getChildComments(parent.id)" :key="child.id" :comment="child"
                        :all-comments="comments" @reply="handleReply" @like="handleLike" />
                </div>
            </template>
        </div>
    </div>
</template>



<style scoped>
.comment-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.comment-form {
    margin-bottom: 30px;
}

.submit-area {
    margin-top: 15px;
    text-align: right;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.child-comments {
    margin-left: 40px;
    border-left: 2px solid #eee;
    padding-left: 20px;
}

.comment-list {
    margin-top: 20px;
}
</style>